﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using AlarmManagePlatform.Model.DB;
using AlarmManagePlatform.Model;

namespace AlarmManagePlatform.DataAccess
{
    internal class tb_AlarminstrumentHisDeailData
    {
        internal void Add(List<Model.DB.tb_AlarminstrumentHisDeailData> tb_AlarminstrumentHisDeailDataList)
        {
            Relations.DBUtility.SqlServer.SqlDb sqlDb = null;
            try
            {
                string sqlScript, currDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                sqlDb = Static.Methods.OpenDataBase();
                foreach (Model.DB.tb_AlarminstrumentHisDeailData tb_AlarminstrumentHisDeailData in tb_AlarminstrumentHisDeailDataList)
                {
                    sqlScript = string.Format("Insert Into tb_AlarminstrumentHisDeailData (InstrumentId,VerificationId,Verificationitemid,HIS_IndexId,His_CreateTime,ParaId,ParaValue,ImageFileInfo,VoiceFileInfo,CreateDate)" +
                    " values ('{0}',{1},{2},{3},'{4}',{5},'{6}','{7}','{8}','{9}');", tb_AlarminstrumentHisDeailData.InstrumentId, tb_AlarminstrumentHisDeailData.VerificationId, tb_AlarminstrumentHisDeailData.Verificationitemid
                    , tb_AlarminstrumentHisDeailData.HIS_IndexId, tb_AlarminstrumentHisDeailData.His_CreateTime, tb_AlarminstrumentHisDeailData.ParaId, tb_AlarminstrumentHisDeailData.ParaValue, tb_AlarminstrumentHisDeailData.ImageFileInfo
                    , tb_AlarminstrumentHisDeailData.VoiceFileInfo, currDateTime);
                    sqlDb.UpdateSqlScript(sqlScript);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("保存检测历史详细数据失败，错误信息：" + ex.Message);
            }
            finally
            {
                if (sqlDb != null)
                    Static.Methods.CloseDataBase(sqlDb);
            }
        }

        internal List<CheckDataInfo> GetCheckDataInfo(string instrumentId, int his_IndexId, string his_CreateTime)
        {
            Relations.DBUtility.SqlServer.SqlDb _SqlDb = null;
            List<CheckDataInfo> _Result;
            CheckDataInfo _CheckDataInfo;
            DataTable _DataTable;
            string _ParaId;
            string _SqlScript = string.Empty;
            string[] _ImageFileItem;
            try
            {
                _DataTable = new DataTable();
                _Result = new List<CheckDataInfo>();

                _SqlScript += "Select * From tb_AlarminstrumentHisDeailData";
                _SqlScript += $"    Where InstrumentId = '{instrumentId}'  And HIS_IndexId = {his_IndexId} And His_CreateTime = '{his_CreateTime}'";
                _SqlScript += "    Order By CreateDate desc , ParaId Asc";
                
                _SqlDb = Static.Methods.OpenDataBase();
                _DataTable = _SqlDb.RunSqlScript(_SqlScript);

                for (int i = 0; i < _DataTable.Rows.Count; i++)
                {
                    _ParaId = _DataTable.Rows[i]["ParaId"].ToString();

                    _CheckDataInfo = new CheckDataInfo();
                    _CheckDataInfo.tb_ParaInfo = new DataAccess.tb_ParaInfo().GetParaInfo(_ParaId);

                    _CheckDataInfo.Unit = string.Empty;
                    _CheckDataInfo.id = int.Parse(_DataTable.Rows[i]["id"].ToString());
                    _CheckDataInfo.InstrumentId = instrumentId;
                    _CheckDataInfo.HIS_IndexId = his_IndexId;
                    _CheckDataInfo.ParaValue = _DataTable.Rows[i]["ParaValue"].ToString();
                    _CheckDataInfo.CreateDate = _DataTable.Rows[i]["His_CreateTime"].ToString();
                    _CheckDataInfo.VerificationId = int.Parse(_DataTable.Rows[i]["VerificationId"].ToString());
                    _CheckDataInfo.Verificationitemid = (Model.SystemEnum.VerificationItem)int.Parse(_DataTable.Rows[i]["Verificationitemid"].ToString());
                    _Result.Add(_CheckDataInfo);

                    _ImageFileItem = _DataTable.Rows[i]["ImageFileInfo"].ToString().Split(',');
                    if (_ImageFileItem.Length > 0)
                    {
                        for (int j = 0; j < _ImageFileItem.Length; j++)
                        {
                            if (!string.IsNullOrWhiteSpace(_ImageFileItem[j]))
                                _CheckDataInfo.ImageFileInfo.Add(_ImageFileItem[j]);
                        }
                    }
                }
                return _Result;
            }
            catch (Exception ex)
            {
                throw new Exception("获取检测历史详细数据失败，错误信息：" + ex.Message);
            }
            finally
            {
                if (_SqlDb != null)
                    Static.Methods.CloseDataBase(_SqlDb);
            }
        }

        internal List<Model.DB.tb_AlarminstrumentHisDeailData> getAlarminstrumentHisDeailData(string InstrumentId,int HIS_IndexId,string His_CreateTime)
        {
            Relations.DBUtility.SqlServer.SqlDb sqlDb = null;
            try
            {
                List<Model.DB.tb_AlarminstrumentHisDeailData> result = new List<Model.DB.tb_AlarminstrumentHisDeailData>();

                Model.DB.tb_AlarminstrumentHisDeailData _Temp;
                string sqlScript = string.Format("select Id,InstrumentId,VerificationId,Verificationitemid,HIS_IndexId,His_CreateTime,ParaId,ParaValue,CreateDate from tb_AlarminstrumentHisDeailData where InstrumentId = '{0}',HIS_IndexId = {1},His_CreateTime = '{2}';"
                    ,InstrumentId,HIS_IndexId,His_CreateTime);
                DataTable dataTable;
                sqlDb = Static.Methods.OpenDataBase();
                dataTable = sqlDb.RunSqlScript(sqlScript);
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {

                    _Temp = new Model.DB.tb_AlarminstrumentHisDeailData();

                    //_Temp.CreateDate = DateTime.Parse(dataTable.Rows[i]["CreateDate"].ToString());
                    if (!string.IsNullOrEmpty(dataTable.Rows[i]["CreateDate"].ToString()))
                        _Temp.CreateDate = DateTime.Parse(dataTable.Rows[i]["CreateDate"].ToString()).ToString(Static.ParaInfo.DateFormatLong);
                    
                    //_Temp.His_CreateTime = DateTime.Parse(dataTable.Rows[i]["His_CreateDate"].ToString());
                    if (!string.IsNullOrEmpty(dataTable.Rows[i]["His_CreateDate"].ToString()))
                        _Temp.His_CreateTime = DateTime.Parse(dataTable.Rows[i]["His_CreateDate"].ToString()).ToString(Static.ParaInfo.DateFormatLong);

                    _Temp.HIS_IndexId = int.Parse(dataTable.Rows[i]["HIS_IndexId"].ToString());
                    _Temp.InstrumentId = dataTable.Rows[i]["InstrumentId"].ToString();
                    _Temp.ParaId = int.Parse(dataTable.Rows[i]["ParaId"].ToString());
                    _Temp.ParaValue = dataTable.Rows[i]["ParaValue"].ToString();
                    _Temp.VerificationId = int.Parse(dataTable.Rows[i]["VerificationId"].ToString());
                    _Temp.Verificationitemid = int.Parse(dataTable.Rows[i]["Verificationitemid"].ToString());

                    result.Add(_Temp);
                }

                return result;
            }
            catch (Exception ex)
            {
                throw new Exception("获取检测历史详细数据失败，错误信息：" + ex.Message);
            }
            finally
            {
                if (sqlDb != null)
                    Static.Methods.CloseDataBase(sqlDb);
            }
        }
        
        internal Model.DB.tb_ParaInfo GetParaInfo(string instrumentId, string createTime)
        {
            Relations.DBUtility.SqlServer.SqlDb _SqlDb = null;
            Model.DB.tb_ParaInfo _Result;
            string _FirstValue = string.Empty;
            string _SqlScript = string.Empty; ;
            try
            {
                _Result = new Model.DB.tb_ParaInfo();

                _SqlScript += "Select ParaId From tb_AlarminstrumentHisDeailData";
                _SqlScript += $"     Where His_CreateTime = '{createTime}' And InstrumentId = '{instrumentId}'";
                _SqlDb = Static.Methods.OpenDataBase();
                _FirstValue = _SqlDb.RunSqlScriptReturnScalar(_SqlScript);

                if (!string.IsNullOrEmpty( _FirstValue))
                    _Result = new DataAccess.tb_ParaInfo().GetParaInfo(_FirstValue);
                else
                    _Result = null;

                return _Result;
            }
            catch (Exception ex)
            {
                throw new Exception("获取参数信息失败，错误信息：" + ex.Message);
            }
            finally
            {
                if (_SqlDb != null)
                    Static.Methods.CloseDataBase(_SqlDb);
            }
        }

        internal void DeleteAlarminstrumentHisDeail(List<string> listInstrumentId)
        {

            Relations.DBUtility.SqlServer.SqlDb _SqlDb = null;
            string _InstrumentIds = string.Empty;
            string _SqlScript = string.Empty;
            try
            {
                _SqlDb = Static.Methods.OpenDataBase();
                _InstrumentIds = Static.Methods.CombiningStrings1<string>(listInstrumentId);

                _SqlScript = "Delete From tb_AlarminstrumentHisDeailData";
                _SqlScript += $" Where InstrumentId in ( {_InstrumentIds} )";

                _SqlDb.UpdateSqlScript(_SqlScript);
            }
            catch (Exception ex)
            {
                throw new Exception("获取删除检测历史详细数据失败，错误信息：" + ex.Message);
            }
            finally
            {
                if (_SqlDb != null)
                    Static.Methods.CloseDataBase(_SqlDb);
            }
        }

        internal void DeleteAlarminstrumentHisDeail(string instrumenrtId, string createTime)
        {
            Relations.DBUtility.SqlServer.SqlDb _SqlDb = null;
            string _SqlScript = string.Empty;
            try
            {
                _SqlDb = Static.Methods.OpenDataBase();

                _SqlScript = "Delete From tb_AlarminstrumentHisDeailData";
                _SqlScript += $" Where InstrumentId = '{instrumenrtId}' And CreateDate = '{createTime}'";

                _SqlDb.UpdateSqlScript(_SqlScript);
            }
            catch (Exception ex)
            {
                throw new Exception("获取删除检测历史详细数据失败，错误信息：" + ex.Message);
            }
            finally
            {
                if (_SqlDb != null)
                    Static.Methods.CloseDataBase(_SqlDb);
            }
        }

        internal string GetHisCreateTime(string instrumentId, int paraId)
        {
            Model.DB.tb_AlarminstrumentHisDeailData _Result = GetAlarminstrumentHisDeailDataFirst(instrumentId,paraId,string.Empty);
            if (_Result != null)
                return _Result.His_CreateTime;
            else
                return string.Empty;
        }


        internal Model.DB.tb_AlarminstrumentHisDeailData GetAlarminstrumentHisDeailDataFirst(string instrumentId, int paraId , string createDate)
        {
            Relations.DBUtility.SqlServer.SqlDb _SqlDb = null;
            DataTable _DataTable;
            List<Model.DB.tb_AlarminstrumentHisDeailData> _Result;
            string _FirstValue = string.Empty;
            string _SqlScript = string.Empty; ;
            try
            {
                _DataTable = new DataTable();
                _Result = new List<Model.DB.tb_AlarminstrumentHisDeailData>();

                _SqlScript = "Select * From tb_AlarminstrumentHisDeailData";
                _SqlScript += "     Where Id > 0 ";

                if(!string.IsNullOrEmpty(instrumentId))
                    _SqlScript += $"    And [InstrumentId] = '{instrumentId}'";

                if (paraId != 0)
                    _SqlScript += $"    And [ParaId] = {paraId}";


                if (!string.IsNullOrEmpty(createDate))
                    _SqlScript += $"    And [CreateDate] = '{createDate}'";


                _SqlScript += $"    Order By [CreateDate] Desc";

                _SqlDb = Static.Methods.OpenDataBase();
                _DataTable = _SqlDb.RunSqlScript(_SqlScript);

                _Result = DataTableToList(_DataTable);

                if (_Result.Count > 0)
                    return _Result[0];
                else
                    return null;
            }
            catch (Exception ex)
            {
                throw new Exception("获取检测历史详细数据失败，错误信息：" + ex.Message);
            }
            finally
            {
                if (_SqlDb != null)
                    Static.Methods.CloseDataBase(_SqlDb);
            }
        }

        private List<Model.DB.tb_AlarminstrumentHisDeailData> DataTableToList(DataTable dataTable)
        {
            List<Model.DB.tb_AlarminstrumentHisDeailData> _Result;
            Model.DB.tb_AlarminstrumentHisDeailData _Temp;
            try
            {
                _Result = new List<Model.DB.tb_AlarminstrumentHisDeailData>();
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    _Temp = new Model.DB.tb_AlarminstrumentHisDeailData();

                    if (!string.IsNullOrEmpty(dataTable.Rows[i]["CreateDate"].ToString()))
                        _Temp.CreateDate = DateTime.Parse(dataTable.Rows[i]["CreateDate"].ToString()).ToString(Static.ParaInfo.DateFormatLong);

                    if (!string.IsNullOrEmpty(dataTable.Rows[i]["His_CreateTime"].ToString()))
                        _Temp.His_CreateTime = DateTime.Parse(dataTable.Rows[i]["His_CreateTime"].ToString()).ToString(Static.ParaInfo.DateFormatLong);

                    _Temp.HIS_IndexId = int.Parse(dataTable.Rows[i]["HIS_IndexId"].ToString());
                    _Temp.InstrumentId = dataTable.Rows[i]["InstrumentId"].ToString();
                    _Temp.ParaId = int.Parse(dataTable.Rows[i]["ParaId"].ToString());
                    _Temp.ParaValue = dataTable.Rows[i]["ParaValue"].ToString();
                    _Temp.VerificationId = int.Parse(dataTable.Rows[i]["VerificationId"].ToString());
                    _Temp.Verificationitemid = int.Parse(dataTable.Rows[i]["Verificationitemid"].ToString());

                    _Result.Add(_Temp);
                }
                return _Result;
            }
            catch (Exception ex)
            {
                throw new Exception("将Datatable转换成List<Model.DB.tb_AlarminstrumentHisDeailData>有异常：" + ex.ToString());
            }
        }
    }
}